<template>
  <j-modal
    :title='title'
    :width='800'
    :visible='visible'
    :maskClosable='false'
    :ok-button-props='{ props: { disabled: disableSubmit } }'
    :fullscreen='true'
    ok-text='提交审批'
    @close='close'
    cancelText='关闭'>
    <template slot="footer">
      <a-button key="back" style='padding-left:8px;padding-right:8px' @click='close(false)'>
        关闭
      </a-button>
      <a-popconfirm :disabled='disableSubmit' title='确定保存吗?' @confirm="() => savePlan()">
        <a-button key="save" style='padding-left:8px;padding-right:8px' :disabled='disableSubmit'>
          保存
        </a-button>
      </a-popconfirm>
      <a-button key="submit" type="primary" style='padding-left:8px;padding-right:8px' :disabled='disableSubmit'
                @click='close(true)'>
        提交审批
      </a-button>
    </template>
    <div style='margin:0 auto;' :class='{isCheck:isCheck}'>
      <a-form-model ref="form" :rules="validatorRules" :model="model">
        <table class='table table-striped table-bordered' align='center' valign='center'>
          <tr>
            <td class='column title' colspan='12'>基本信息</td>
          </tr>
          <tr>
            <td class='column'>计划编号</td>
            <td class='value'>
              <a-input v-model='model.number' placeholder='系统生成' :disabled='true'></a-input>
            </td>
            <td class='column item-required'>计划年度</td>
            <td class='value'>
              <a-form-model-item label="" prop="planYear">
                <a-date-picker
                  mode='year'
                  placeholder='请选择年份'
                  format='YYYY'
                  value-format='yyyy-MM-dd'
                  v-model='model.planYear' 
                  :open='yearPickShow'
                  :disabled='disableSubmit'
                  style='width: 100%'
                  @panelChange='handlePanelChange'
                  @openChange='handleOpenChange'/>
              </a-form-model-item>
            </td>
            <td class='column item-required'>计划名称</td>
            <td class='value'>
              <a-form-model-item label="" prop="name">
                <a-input v-model='model.name' :disabled='disableSubmit'></a-input>
              </a-form-model-item>
            </td>
            <td class='column item-required'>计划负责人</td>
            <td class='value'>
              <a-form-model-item v-if="!disableSubmit" label="" prop="principal">
                <a-select v-model="model.principal"  :disabled='disableSubmit'>
                  <a-select-option v-for='(item,index) in principalData' :key='item.id' :value="item.userId">
                    {{ item.userName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-input v-else v-model='model.principalText' :disabled='true'></a-input>
            </td>
          </tr>
          <tr>
            <td class='column'>审计单位</td>
            <td class='value' colspan='7'>
              <a-form-model-item label="" prop="remidText">
                <a-input v-if='organShow' @click.native='openOrganModel'
                         v-model='model.remidText'
                         :disabled='true'></a-input>
              </a-form-model-item>
            </td>
          </tr>
          <tr>
            <td class='column item-required' colspan='1'>临时审计工作目标</td>
            <td class='value' colspan='7'>
              <a-form-model-item label="" prop="aims">
                <a-input v-model='model.aims' :disabled='disableSubmit'></a-input>
              </a-form-model-item>
            </td>
          </tr>
          <tr>
            <td class='column' colspan='12'>审计项目计划明细</td>
          </tr>
          <tr>
            <td class='value' colspan='12' style='padding:0;'>
              <a-table
                class='edit-list'
                size='middle'
                bordered
                :columns='columns1'
                :dataSource='dataSource1'
                :pagination='ipagination1'
                :scroll='{ x: 200, y: 240 }'>
                <span slot="actionName">
                  <a-button v-if='!disableSubmit' style='padding:0 7px' size="small" @click="addPlanList('临时审计计划制定-新增')"
                            type="primary" icon="plus">新增</a-button>
                  {{disableSubmit?'操作':''}}
                </span>
                <span v-if="enterStatus != '1'" slot='action' slot-scope='text, record'>
                  <a @click="handleCheck(record,'计划明细-查看')">查看</a>
                  <a-divider style='margin:0 8px' type='vertical'/>
                  <a-dropdown>
                    <a class='ant-dropdown-link'>更多 <a-icon type='down'/></a>
                    <a-menu slot='overlay'>
                      <a-menu-item v-if="model.status != '3'">
                        <a style='text-align: center' @click="handleEdit(record,'计划明细-编辑')">编辑</a>
                      </a-menu-item>
                      <a-menu-item v-if="model.status != '3'">
                        <a-popconfirm title='确定删除吗?' @confirm='() => changeDelete(record.id)'>
                          <a style='text-align: center'>删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </span>
              </a-table>
            </td>
          </tr>
          <tr>
            <td class='column' colspan='12'>审核记录</td>
          </tr>
          <tr>
            <td class='value' colspan='12' style='padding:0;'>
              <a-table
                class='edit-list'
                size='middle'
                bordered
                :columns='columns3'
                :dataSource='dataSource3'
                :pagination='ipagination3'
                :scroll='{ x: 200, y: 240 }'>
              </a-table>
            </td>
          </tr>
        </table>
      </a-form-model>
    </div>
    <!-- table区域-end -->
    <OrganModal ref='departModal' @ok='updateQueryParam'></OrganModal>
    <PlanDetails ref='modalForm' :status="model.status" @ok='savePlanSuccess'></PlanDetails>
    <SelectApprove ref='approver' @submitData='submitData'></SelectApprove>
  </j-modal>
</template>
<script>
  import {httpAction, getAction, postAction, deleteAction} from '@/api/manage'
  import OrganModal from '../../components/OrganModal'
  import SelectApprove from '../publicModel/SelectApprover'
  import PlanDetails from './PlanDetails'
  import moment from 'moment'
  import columns1 from './columns1'
  import columns3 from './columns3'
  import {JeecgListMixin} from '@/mixins/JeecgListMixin'
  import store from '@/store/'

  export default {
    name: 'NdsjjhzdModal',
    mixins: [JeecgListMixin],
    components: {
      OrganModal,
      PlanDetails,
      SelectApprove
    },
    data() {
      return {
        enterStatus: '0',
        disableSubmit: false,
        title: '机构信息',
        visible: false,
        isCheck: false,
        url: {
          get: '/sjzyzhgl/sjPlanInfo/planInfoList',
          add: '/sjzyzhgl/sjResourceAuditors/add',
          edit: '/sjzyzhgl/sjResourceAuditors/edit',
          list: '/sjzyzhgl/sjPlanProjectInfo/projectInfoByProId',
          approveList: '/sjzyzhgl/sjApplyLog/queryApplyLogListByPId',//审批记录列表
          submitData: '/common/sjProcCommon/subShen',
          secondSubmit: '/common/sjProcCommon/doapply',
          addTitle: '/sjzyzhgl/sjPlanInfo/addReturnId',
          updataTitle: '/sjzyzhgl/sjPlanInfo/edit',
          delete: '/sjzyzhgl/sjPlanProjectInfo/delete',
          queryPlanUserInfo:'/sjzyzhgl/sjPlanInfo/queryPlanUserInfo',
        },
        organShow: true,
        model: {},
        yearPickShow: false,
        columns1: columns1(this),
        columns3: columns3(this),
        dataSource1: [],
        dataSource3: [],
        ipagination1: {
          current: 1,
          pageSize: 10,
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          onChange: (pageNumber) => {
            this.onChange1(pageNumber)
          },
          showQuickJumper: true,
          total: 0
        },
        ipagination3: {
          current: 1,
          pageSize: 10,
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          onChange: (pageNumber) => {
            this.onChange3(pageNumber)
          },
          showQuickJumper: true,
          total: 0
        },
        approverId: '',
        validatorRules: {
          principal: [{ required: true, message: '请选择!' }],
          planYear: [
            {required: true, message: '请选择!'},
          ],
          name: [
            {required: true, message: '请选择!'},
          ],
          remidText: [
            {required: true, message: '请选择!'},
          ],
          aims: [
            {required: true, message: '请选择!'},
          ]
        },
        principalData:[],
        defaultValue:null,
      }
    },
    methods: {
      add() {
        this.queryPlanUserInfo(null, (result) => {
          this.model = {
            principal: result[0].userId,
            remidText: store.getters.departInfo.departName,
            remid: store.getters.departInfo.id,
            planYear: ''
          }
          this.dataSource1 = []
          this.dataSource3 = []
          this.visible = true
          this.enterStatus = '0'
        })
      },
      check(record) {
        this.model = Object.assign({}, record)
        this.visible = true
        this.enterStatus = '1'
        this.httpRequest()
        this.list1()
        this.list3()
      },
      edit(record) {
        this.queryPlanUserInfo(record.createBy, (result) => {
          this.model = Object.assign({}, record)
          this.visible = true
          this.enterStatus = '2'
          this.httpRequest()
          this.list1()
          this.list3()
        })
      },

      queryPlanUserInfo(userId, callBack) {
        getAction(this.url.queryPlanUserInfo, { userId: userId })
          .then((res) => {
            if (res.success && res.result) {
              if (res.result && res.result.length > 0) {
                this.principalData = res.result
                callBack(res.result)
              } else {
                this.$message.error('未设置审计部部长，请联系本单位审计负责人')
              }
            } else {
              this.$message.error('获取审计部部长异常，请联系本单位审计负责人')
            }
          })
          .finally(() => {
          })
      },

      // 获取计划头部信息
      httpRequest() {
        getAction(this.url.get, {id: this.model.id}).then((res) => {
          if (res.success && res.result) {
            this.model = res.result.records[0]
          } else {
            console.log(res)
          }
        }).finally(() => {
        })
      },
      // 点击关闭或提交审核
      close(isSubmit) {
        if (isSubmit) { //点击提交审批
          this.$refs.approver.showApproveConfirm = true
        } else {
          this.visible = false
        }
      },
      // 提交审核
      submitData(id) {
        let httpurl = this.url.submitData
        let param = {
          proId: this.model.id,
          userIds: id
        }
        if (this.model.status == '3') {
          httpurl = this.url.secondSubmit
        } else {
          param.type = '2'
        }
        getAction(httpurl, param).then((res) => {
          if (res.success && res.result) {
            this.$message.success('审批已启动成功');
            this.visible = false
            this.$emit('ok')
          } else {
          }
        })
      },
      // 保存计划
      saveData() {
        let httpurl, method
        if (!this.model.id) {
          httpurl = this.url.addTitle
          method = 'post'
        } else {
          httpurl = this.url.updataTitle
          method = 'put'
        }
        return new Promise((resolve, reject) => {
          httpAction(httpurl, {type: '2', ...this.model}, method).then((res) => {
            if (res.success) {
              if (!this.model.id) {
                this.model.id = res.result
              }
              resolve(res.success)
            } else {
              reject(res.success)
              this.$message.error(res.message)
            }
          }).finally(() => {

          })

        });
      },
      savePlan() {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.saveData().then((data) => {
              if (data) {
                this.$message.success('草案保存成功');
                this.$emit('ok')
                this.visible = false
              }
            })
          } else {
            return false
          }
        })
      },
      // 新增或调增计划项目
      addPlanList(name) {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.saveData().then((data) => {
              if (data) {
                this.$refs.modalForm.proId = this.model.id
                this.$refs.modalForm.title = name
                this.$refs.modalForm.submitState = this.model.status
                this.$refs.modalForm.secondState = this.model.upstate
                this.$refs.modalForm.disableSubmit = false
                this.$refs.modalForm.add()
              }
            })
          } else {
            return false
          }
        })
      },
      // 删除计划项目
      changeDelete: function (id) {
        if (!this.url.delete) {
          this.$message.error("请设置url.delete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            //重新计算分页问题
            that.reCalculatePage(1)
            that.$message.success(res.message);
            this.list1()
            this.list2()
          } else {
            that.$message.warning(res.message);
          }
        });
      },
      // 机构列表弹窗
      openOrganModel() {
        this.$refs.departModal.show()
        this.$refs.departModal.selectedKeys = [this.model.remid]
      },
      // 确认选中机构
      updateQueryParam(data) {
        this.model.remidText = data.departName
        this.model.remid = data.id
        this.organShow = false
        this.$nextTick(() => {
          this.organShow = true
        })
      },
      list1() {
        getAction(this.url.list, {
          proId: this.model.id,
          pageSize: this.ipagination1.pageSize,
          pageNo: this.ipagination1.current,
          operationFlag: 'normal'
        }).then((res) => {
          if (res.success && res.result) {
            this.dataSource1 = res.result.records
            this.ipagination1.total = res.result.total
          } else {
            this.ipagination1.total = 0
          }
        })
      },
      list3() {
        getAction(this.url.approveList, {
          pid: this.model.id,
          pageSize: this.ipagination3.pageSize,
          pageNo: this.ipagination3.current,
        }).then((res) => {
          if (res.success && res.result) {
            this.dataSource3 = res.result.records
            this.ipagination3.total = res.result.total
          } else {
            this.ipagination3.total = 0
          }
        })
      },
      // 分页
      onChange1(pageNumber) {
        this.ipagination1.current = pageNumber
        this.list1()
      },
      onChange2(pageNumber) {
        this.ipagination2.current = pageNumber
        this.list2()
      },
      onChange3(pageNumber) {
        this.ipagination3.current = pageNumber
        this.list3()
      },
      // 弹出日历和关闭日历的回调
      handleOpenChange(status) {
        this.yearPickShow = status
      },
      moment,
      // 得到年份选择器的值
      handlePanelChange(value) {
        this.model.planYear = moment(value).format('YYYY')
        this.yearPickShow = false
        this.$refs.form.validateField('planYear', (error) => {
          console.log(error)
        })
      },
      // 计划项目新增成功
      savePlanSuccess() {
        this.list1()
        this.list2()
        this.list3()
      },
    }
  }
</script>

<style lang='less' scoped>
  @import '../../css/checkAndEdit.less';
  /deep/ .ant-table-hide-scrollbar {
    scrollbar-color: unset !important;
    margin-bottom: -10px !important;
  }
</style>
